import axios from 'axios'
import qs from 'qs'
import store from '../store'
import config from '../config'
import { getDomain } from '@/libs/tools'
import { loginOther } from '@/libs/util'
import { Toast } from 'vant'

const addErrorLog = errorInfo => {
  // TODO 对错误日志进行收集
}

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }

  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'Content-Type': 'application/json; charset=utf-8'
      }
    }
    return config
  }

  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // TODO页面取消正在加载的特效
    }
  }

  interceptors (instance, options) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // TODO根据不同框架添加不同的加载特效
      }
      this.queue[options.url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(options.url)
      const { data, status } = res
      Toast.clear()
      // 对跨域提示未登录进行处理
      if (getDomain(options.url)) {
        if (data.errcode === 1001) {
          loginOther(function () {
            location.reload()
          })
        }
      } else {
        if (data.errcode === 1001) {
          let self_url = encodeURIComponent(window.location.href.replace(/#/g, '$'))
          let type = ''
          if (options.goApi) {
            type = '&type=' + options.goApi
            if (options.goApi == 'api5') {
              if (self_url.indexOf('subsidy-swj-index-v2') !== -1) {
                self_url = encodeURIComponent('https://shengst.tripln.top/$/subsidy-swj-index-v2')
              } else if (self_url.indexOf('subsidy-book-index') !== -1) {
                self_url = encodeURIComponent('https://shengst.tripln.top/$/subsidy-book-index')
              } else if (self_url.indexOf('subsidy-swj-my-card') !== -1) {
                self_url = encodeURIComponent('https://shengst.tripln.top/$/subsidy-swj-my-card')
              }
            }
          }
          location.href = this.baseUrl + '/' + (options.goApi ? options.goApi : 'api4') + '/uc/ctc/wechatService/authorize?testip=' + config.testip + type + '&returnUrl=' + self_url
        }
      }
      return { data, status }
    }, error => {
      this.destroy(options.url)
      let errorInfo = error.response
      if (!errorInfo) {
        const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: { responseURL: config.url }
        }
      }
      addErrorLog(errorInfo)
      return Promise.reject(error)
    })
  }

  request (options) {
    // if (options.loading !== true) {
    //   Toast.loading({
    //     mask: true,
    //     message: '加载中...'
    //   })
    // }
    const instance = axios.create()
    if (options.type === 'get') {
      options.method = 'get'
      options.params = options.data
    } else {
      options.method = 'post'
    }

    if (getDomain(options.url)) {
      let url = getDomain(options.url)
      if (store.state.app.juyouTicket[url]) {
        options.headers = { 'juyou-ticket': store.state.app.juyouTicket[url] }
      }
    }
    delete options.type
    if (options.php === true) {
      if (options.headers) {
        options.headers = Object.assign(options.headers, { 'Content-Type': 'application/x-www-form-urlencoded' })
      } else {
        options.headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
      }
      options.data = qs.stringify(options.data)
    }
    options.withCredentials = true

    options = Object.assign(this.getInsideConfig(), options)

    this.interceptors(instance, options)
    if (options.await === true) {
      return new Promise((resolve, reject) => {
        instance(options)
          .then((response) => {
            resolve(response)
          })
          .catch((error) => {
            reject(error)
          })
      })
    } else {
      return instance(options)
    }
  }
}

export default HttpRequest
